<template>
    <div class="pool-list">
        <div class="move-box">
            <RiskLeftStockPool
                v-model="inputValueLeft"
                @on-submit="submitInput"
                @on-handleNode="clickNode"
                :placeholders="ltitleName"
                :treeData="treeData"
                :selectData="tradeTypeArr"
                :leftHeight="leftHgt"
                :currentKey="currentKey"
                :defaultExpandedKeys="defaultExpandedKeys"
                v-loading="treeLoading"
            >
                <template slot="ltitle">证券池信息</template>
            </RiskLeftStockPool>

            <!-- 证券池信息 -->
            <template v-if="cutInfo === '本地' || cutInfo === '外部'">
                <RiskRightModule v-model="inputValueRight" :rightPlace="rtitleName" :rightHeight="leftHgt" @on-keyup="handleSearchPool">
                    <p slot="rtitle">证券池信息</p>
                    <span slot="button" class="dict-r-slot">
                        <el-select v-model="selectSourceType" placeholder="来源类型" size="mini" class="selectStyle" v-show="cutInfo === '外部'">
                            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"> </el-option>
                        </el-select>
                        <el-button type="primary" size="mini" @click="handleSearchPool">查询</el-button>
                    </span>
                    <span slot="button" class="dict-r-slot">
                        <el-button type="primary" size="mini" v-authCode.show="B_0118" v-show="cutInfo === '本地'" @click="addGroup">新增</el-button>
                    </span>
                    <span slot="button" class="dict-r-slot">
                        <el-button type="primary" size="mini" v-authCode.show="B_0142" @click="downLoadGroupFile">导出</el-button>
                    </span>
                    <span slot="button" class="dict-r-slot">
                        <el-button type="danger" size="mini" v-authCode.show="B_0119" v-show="cutInfo === '本地'" @click="deleteGroup"
                            >删除</el-button
                        >
                    </span>
                    <slot>
                        <el-table
                            :data="tableData"
                            border
                            size="mini"
                            style="width: 100%"
                            height="79vh"
                            @selection-change="handleSelectionChange"
                            v-loading="tableLoading"
                            @sort-change="handlePoolTableSort"
                        >
                            <el-table-column type="selection" width="55" size="mini" align="center"> </el-table-column>
                            <el-table-column prop="stGrCode" label="证券池编码" sortable="custom" show-overflow-tooltip> </el-table-column>
                            <el-table-column prop="stGrName" label="证券池名称" sortable="custom" show-overflow-tooltip> </el-table-column>
                            <el-table-column prop="sourceType" label="数据来源" sortable="custom" show-overflow-tooltip>
                                <template slot-scope="scope">
                                    <span>{{ Dict.SourceType[scope.row.sourceType] }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column
                                prop="dtCtDate"
                                label="创建日期"
                                sortable="custom"
                                show-overflow-tooltip
                                align="center"
                            >
                                <template slot-scope="scope">
                                    <span>{{ dateFormat(scope.row.dtCtDate) }} {{ timeFormat(scope.row.dtCtTime) }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="dtCtUser" label="创建者" sortable="custom" show-overflow-tooltip v-if="showParamByDocking()">
                            </el-table-column>
                            <el-table-column label="操作" width="120">
                                <template slot-scope="scope">
                                    <RiskIconButton
                                        type="primary"
                                        icon="el-icon-edit"
                                        v-authCode="B_0120"
                                        topTitle="编辑证券池"
                                        :disabled="cutInfo == '外部'"
                                        @on-click="editGroupRow(scope.row)"
                                    ></RiskIconButton>
                                    <RiskIconButton
                                        type="danger"
                                        icon="el-icon-delete"
                                        v-authCode="B_0119"
                                        topTitle="删除证券池"
                                        :disabled="cutInfo == '外部'"
                                        @on-click="deleteGroupRow(scope.row)"
                                    ></RiskIconButton>
                                </template>
                            </el-table-column>
                        </el-table>
                        <div class="block">
                            <risk-pagination :paging="groupPage" @page-change="poolCurrentChange"></risk-pagination>
                        </div>
                    </slot>
                </RiskRightModule>
                <!-- 新增 -->
                <yh-dialog drag :title="groupDialog.title" :visible.sync="groupDialog.visible" width="400px" v-loading="loading">
                    <el-form label-width="140px" size="mini">
                        <el-form-item label="证券池编号">
                            <el-input placeholder="自动生成" style="width: 220px" disabled v-model="groupData.stGrCode"></el-input>
                        </el-form-item>
                        <el-form-item label="证券池名称">
                            <el-input style="width: 220px" v-model="groupData.stGrName"></el-input>
                        </el-form-item>
                        <el-form-item label="数据来源">
                            <el-input style="width: 220px" v-model="sourceType" disabled></el-input>
                        </el-form-item>
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        <el-button size="mini" @click="groupDialogClosed"> 取 消 </el-button>
                        <el-button size="mini" type="primary" @click="groupDialogConfirm"> 确 定 </el-button>
                    </div>
                </yh-dialog>
            </template>

            <!-- 证券池明细 -->
            <template v-else>
                <RiskRightModule v-model="inputDetailValueRight" :rightPlace="right2Place" :rightHeight="leftHgt">
                    <p slot="rtitle"></p>
                    <span slot="button" class="dict-r-slot">
                        <el-button type="primary" size="mini" @click="handleSearchDetail">查询</el-button>
                    </span>
                    <span slot="button" class="dict-r-slot">
                        <el-button
                            type="primary"
                            size="mini"
                            v-authCode.show="B_0121"
                            v-show="this.currentData.sourceType === '1'"
                            @click="editDetail"
                            >编辑</el-button
                        >
                    </span>
                    <span slot="button" class="dict-r-slot">
                        <el-button type="primary" size="mini" v-authCode.show="B_0143" @click="downLoadDetailFile">导出明细</el-button>
                    </span>
                    <span slot="button" class="dict-r-slot">
                        <el-button
                            type="danger"
                            size="mini"
                            v-authCode.show="B_0122"
                            v-show="this.currentData.sourceType === '1'"
                            @click="deleteDetail"
                            >删除</el-button
                        >
                    </span>
                    <slot>
                        <el-table
                            :data="tableData"
                            border
                            size="mini"
                            style="width: 100%"
                            height="79vh"
                            @selection-change="handleSelectionDetailChange"
                            :key="tableDataNum"
                            v-loading="tableLoading"
                            @sort-change="handleStockTableSort"
                        >
                            <el-table-column type="selection" width="55" size="mini" align="center" min-width="120"> </el-table-column>
                            <el-table-column prop="stockCode" label="证券代码" sortable="custom" min-width="120"> </el-table-column>
                            <el-table-column prop="stockNameSt" label="证券简称" sortable="custom" min-width="120" show-overflow-tooltip>
                            </el-table-column>
                            <el-table-column prop="stockType" label="证券类型" sortable="custom" min-width="120" show-overflow-tooltip>
                                <template slot-scope="scope">
                                    <span>{{ stockType[scope.row.stockType] }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="marketCode" label="市场类型" sortable="custom" min-width="120">
                                <template slot-scope="scope">
                                    <!-- <span>{{ getMarketCode(scope.row.marketCode) }}</span> -->
                                    <span>{{ marketCode[scope.row.marketCode] }}</span>
                                </template>
                            </el-table-column>
                            <!-- 维度类别为证券池的时候显示该列 -->
                            <el-table-column
                                v-if="currentData.tradeType == '5' || currentData.stGroupNodeType == 'POOL_TYPE'"
                                prop="stGrName"
                                label="公司证券池"
                                align="center"
                                sortable="custom"
                                min-width="120"
                                show-overflow-tooltip
                            >
                            </el-table-column>
                            <el-table-column
                                v-if="currentData.stGroupNodeType == 'POOL_TYPE'"
                                prop="stockPoolTypeName"
                                label="证券池类型"
                                align="center"
                                sortable="custom"
                                width="120"
                                show-overflow-tooltip
                            >
                            </el-table-column>
                            <el-table-column
                                v-if="currentData.stGroupNodeType == 'POOL_TYPE'"
                                prop="controlDirectionName"
                                label="方向"
                                align="center"
                                sortable="custom"
                                min-width="100"
                                show-overflow-tooltip
                            >
                            </el-table-column>
                            <el-table-column
                                v-if="currentData.stGroupNodeType == 'POOL_TYPE'"
                                prop="beginDate"
                                label="开始日期"
                                align="center"
                                sortable="custom"
                                min-width="120"
                                :formatter="formatterDate"
                                show-overflow-tooltip
                            >
                            </el-table-column>
                            <el-table-column
                                v-if="currentData.stGroupNodeType == 'POOL_TYPE'"
                                prop="endDate"
                                label="结束日期"
                                align="center"
                                sortable="custom"
                                min-width="120"
                                :formatter="formatterDate"
                                show-overflow-tooltip
                            >
                            </el-table-column>
                            <el-table-column
                                prop="dtMdDate"
                                label="添加日期"
                                sortable="custom"
                                min-width="120"
                                align="center"
                            >
                                <template slot-scope="scope">
                                    <span>{{ dateFormat(scope.row.dtMdDate) }} {{ timeFormat(scope.row.dtMdTime) }}</span>
                                </template>
                            </el-table-column>
                            <!-- <el-table-column
                                prop="dtMdTime"
                                label="添加时间"
                                sortable="custom"
                                min-width="120"
                                :formatter="formatterTime"
                                align="center"
                            >
                            </el-table-column> -->
                            <el-table-column prop="dtMdUser" label="添加者" sortable="custom" min-width="120" v-if="showParamByDocking()">
                            </el-table-column>
                        </el-table>
                        <div class="block">
                            <risk-pagination :paging="detailPage" @page-change="detailCurrentChange"></risk-pagination>
                        </div>
                    </slot>
                </RiskRightModule>
                <!-- 明细编辑 -->
                <div>
                    <yh-dialog
                        drag
                        :title="editDetailDialog.title"
                        :visible.sync="editDetailDialog.visible"
                        width="800px"
                        v-loading="loading"
                        class="editDialog"
                    >
                        <RiskTrantableInline
                            leftPlaceholder="编号/名称"
                            rightPlaceholder="编号/名称"
                            indexKey="stockCode"
                            ref="tranTable"
                            sort="stockNameSt"
                            :columns="tranColumns"
                            :rightTableData="rightTranData"
                            :searchNames="['stockCode', 'stockNameSt']"
                            url="/stockPool/stock/queryStock/stocklist"
                            v-if="editDetailDialog.visible"
                            style="min-height: 430px"
                        />
                        <div slot="footer" class="dialog-footer">
                            <el-button size="mini" @click="editDetailDialogClosed"> 取 消 </el-button>
                            <el-button size="mini" type="primary" @click="editDetailDialogConfirm">确 定 </el-button>
                        </div>
                    </yh-dialog>
                </div>
            </template>
        </div>
        <!-- 删除 -->
        <div>
            <yh-dialog drag :title="deleteDialog.title" :visible.sync="deleteDialog.visible" width="500px" v-loading="loading">
                <div class="remove-text">
                    <span v-for="(itme, index) in delPendingData" :key="index"> {{ itme }} , </span>
                </div>
                <div slot="footer" class="dialog-footer">
                    <el-button size="mini" @click="deleteDialogClosed"> 取 消 </el-button>
                    <el-button size="mini" type="primary" @click="deleteDialogConfirm">确 定 </el-button>
                </div>
            </yh-dialog>
        </div>
    </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import DictionConstUtil, { SGU_CACHE } from '@/utils/diction-const-util';
import RiskLeftStockPool from '@/common/components/risk-left-stock-pool.vue';
import RiskRightModule from '@/common/components/risk-right-module.vue';
import RiskIconButton from '@/common/components/risk-icon-button.vue';
import RiskPagination from '@/common/components/risk-pagination.vue';
import XEUtils from 'xe-utils';
import { DialogVO } from '@yhfin/biz';
import Dict from './dict/index';
import { downLoadFile } from '@/utils/request';
import RiskTrantableInline from '@/common/components/risk-trantable-inline.vue';
import { getCurrentPageData, formatterDate, formatterTime, getConfigItem, showParamByDocking, timeFormat, dateFormat } from '@/utils/tools';
import { languages } from 'monaco-editor';
import json = languages.json;
export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}

@Component({
    name: 'StockPool',
    components: {
        RiskLeftStockPool,
        RiskRightModule,
        RiskIconButton,
        RiskTrantableInline,
        RiskPagination,
    },
})
export default class StockPool extends Vue {
    formatterDate = formatterDate;
    formatterTime = formatterTime;
    dateFormat = dateFormat;
    timeFormat = timeFormat;
    showParamByDocking = showParamByDocking;
    private inputValueLeft: string = '';
    private ltitleName: string = '编号/名称';
    private leftHgt: string = '100vh';
    private inputValueRight: string = '';
    private inputDetailValueRight: string = '';

    private rtitleName: string = '证券池编码/名称';
    private right2Place: string = '证券代码/名称';

    private localList: any[] = []; // 本地数据

    private outsideList: any[] = []; // 外部数据

    private groupDialog: DialogVO = new DialogVO();
    private deleteDialog: DialogVO = new DialogVO();
    private editDetailDialog: DialogVO = new DialogVO();

    private tranColumns: any[] = [
        {
            label: '编号',
            prop: 'stockCode',
            width: 100,
        },
        {
            label: '名称',
            prop: 'stockNameSt',
            width: 145,
        },
    ];
    private rightTranData: any[] = [];

    private groupDataBackup: any = {};
    private sourceType: string = '风控';
    private cutInfo: string = '外部';
    private currentData: any = {};

    private tableData: any[] = []; // 分页后的数据

    private tableDataList: any[] = []; // 表格总数据

    private tableDataSearched: any[] = []; // 搜索后的表格数据

    private hasSelectedData: any[] = []; // 勾选的数据Id

    private delPendingData: any[] = []; // 待删除的数据Id

    Dict: any = new Dict();

    private statusOptions = this.Dict.statusOptions;
    private marketCode: any = {};
    private stockType: any = {};
    private tableDataNum: number = 1;
    private currentKey: any = 2;
    private defaultExpandedKeys: any[] = [2];

    private selectSourceType: string = ''; // 来源类型(外部)

    // 来源类型下拉框可选
    private options: any[] = [];
    // 来源类型1
    private options1: any[] = [
        {
            value: '',
            label: '全部',
        },
        {
            value: '2',
            label: '恒生-主动',
        },
        {
            value: '5',
            label: '恒生-被动',
        },
    ];

    // 来源类型2 适用于淡水泉项目，淡水泉没有恒生的
    private options2: any[] = [
        {
            value: '',
            label: '全部',
        },
        {
            value: '9',
            label: '淡水泉jcs数据中心',
        },
    ];
    private groupData: any = {
        stGrCode: '自动生成',
        stGrName: '',
    };
    private groupPage: pages = {
        currentPage: 1,
        pageSize: 50,
        total: 0,
    };
    private detailPage: pages = {
        currentPage: 1,
        pageSize: 50,
        total: 0,
    };
    private treeData: any[] = [
        // {
        //     id: '-1',
        //     label: '本地',
        //     children: [],
        // },
        // {
        //     id: '-1',
        //     label: '外部',
        //     children: [],
        // },
    ];
    // 维度类别下拉框码值
    private tradeTypeArr: any[] = [];
    // 证券池 tradeType为5, 从产品信息表查的和证券池表数据的相关，格式为fundCode_对应name
    private fundCodeTradeTypeArr: any = [];
    // 全部的关联的产品信息code
    private fundCodeArr: any[] = [];
    // 证券池后端单独加入的数据的标识，虚假的数据，只是为了显示结构
    FALSE_DATA = 'falseData20220920';
    // 前缀
    PRE_FALSE = '$$';

    private StockPoolTypeStorage: any[] = []; // 证券池类型类型
    private tableLoading: boolean = false; // 表格加载
    private treeLoading: boolean = false; // 树加载
    private fundChildIds: any[] = [];
    private sortParam1: string = '';
    private sortParam2: string = '';

    // 排序参数
    private sortParamObj1 = {
        stGrCode: 'C_ST_GR_CODE',
        stGrName: 'C_ST_GR_NAME',
        sourceType: 'C_SOURCE_TYPE',
        dtCtDate: 'CONCAT(D_DT_CT_DATE,D_DT_CT_TIME)',
        dtCtUser: ' C_DT_CT_USER',
    };

    // 排序参数
    private sortParamObj2 = {
        stockCode: 'C_STOCK_CODE',
        stockNameSt: 'C_STOCK_NAME_ST',
        stockType: 'C_STOCK_TYPE',
        marketCode: 'C_MARKET_CODE',
        stGrName: 'C_ST_GR_NAME',
        stockPoolType: 'C_STOCK_POOL_TYPE',
        stockPoolTypeName: 'C_STOCK_POOL_TYPE_NAME',
        controlDirection: 'C_CONTROL_DIRECTION',
        controlDirectionName: 'C_CONTROL_DIRECTION_NAME',
        beginDate: 'D_BEGIN_DATE',
        endDate: 'D_END_DATE',
        dtMdDate: 'CONCAT(D_DT_MD_DATE,D_DT_MD_TIME)',
        dtMdTime: 'D_DT_MD_TIME',
        dtMdUser: 'C_DT_MD_USER',
    };

    private tableKey: number = 0;
    private docking: string = '';

    async mounted() {
        this.queryFundCodeTradeType5();
        this.getDictionaryData('Y_000281');
        const marketType = await SGU_CACHE('MarketType', '/dict/market/list', []);
        this.marketCode = DictionConstUtil.ListToPojo(marketType);
        const stockType = await SGU_CACHE('StockType', '/dict/stockType/list', []);
        this.stockType = DictionConstUtil.ListToPojo(stockType);
        // 证券池类型
        this.StockPoolTypeStorage = await SGU_CACHE('StockPoolType', '/dict/list/code/Y_000290', []);
        this.groupDataBackup = JSON.parse(JSON.stringify(this.groupData));
        // this.getStockInfo();

        // 查询左侧目录树
        // this.getStockPoolTree();
        setTimeout(() => {
            this.queryStockPoolList({ stGrName: '外部' });
        }, 100);
        // 获取当前环境
        this.docking = getConfigItem('WEB_DOCKING');
        if (this.docking !== 'SPRINGSCAPITAL') {
            this.options = this.options1;
        } else {
            this.options = this.options2;
        }
    }

    // 查询所有证券池(基础树)
    // getStockPoolTree() {
    //     // this.treeLoading = true;
    //     this.$axios
    //         .post('/stockPool/stGroup/tree', {
    //             keyword: '',
    //             tradeType: '',
    //         })
    //         .then((res: any) => {
    //             this.treeData = res;
    //             // this.treeLoading = false;
    //             // this.treeData[1].forEach(ele => {});
    //         })
    //         .catch(() => {
    //             // this.treeLoading = false;
    //         });
    // }

    // 转义市场类型
    private getMarketCode(value): string {
        let ret = '';
        for (let item of this.marketCode) {
            if (item.dictKey === value) {
                ret = item.dictKeyName;
            }
        }
        return ret;
    }

    // 分组分页切换
    // private groupPageChange(): void {
    //     if (this.inputValueRight || (this.selectSourceType && this.cutInfo === '外部')) {
    //         this.groupPage.total = this.tableDataSearched.length;
    //         this.tableData = getCurrentPageData(this.tableDataSearched, this.groupPage.currentPage, this.groupPage.pageSize);
    //     } else {
    //         let list = this.tableDataList.filter(item => !(item.operatorName == this.FALSE_DATA));
    //         this.groupPage.total = list.length;
    //         this.tableData = getCurrentPageData(list, this.groupPage.currentPage, this.groupPage.pageSize);
    //     }
    //     this.tableDataNum++;
    // }

    // 明细分页
    // private detailPageChange(): void {
    //     if (this.inputDetailValueRight) {
    //         this.detailPage.total = this.tableDataSearched.length;
    //         this.tableData = getCurrentPageData(this.tableDataSearched, this.detailPage.currentPage, this.detailPage.pageSize);
    //     } else {
    //         this.detailPage.total = this.tableDataList.length;
    //         this.tableData = getCurrentPageData(this.tableDataList, this.detailPage.currentPage, this.detailPage.pageSize);
    //     }
    //     this.tableDataNum++;
    // }

    //   证券池信息
    // private getStockInfo(): void {
    //     this.$axios.get('/stockPool/stGroup/all').then((res: any) => {
    //         let local = [];
    //         let outside = [];
    //         this.localList = [];
    //         this.outsideList = [];
    //         for (let item of res) {
    //             if (item.sourceType === '1') {
    //                 local.push(item);
    //                 let datas = item.stGrCode + '-' + item.stGrName;
    //                 this.localList.push(Object.assign({ label: datas, id: item.stGrCode }, item));
    //             } else {
    //                 outside.push(item);
    //                 let datas = item.stGrCode + '-' + item.stGrName;
    //                 this.outsideList.push(Object.assign({ label: datas, id: item.stGrCode }, item));
    //             }
    //         }
    //         this.treeData[0].children = this.localList;
    //         // 树
    //         this.treeData[1].children = this.toTreeData(this.outsideList);
    //         this.tableDataList = this.cutInfo == '外部' ? this.outsideList : this.localList;
    //         this.selectGroup();
    //     });
    // }

    // 分页处理
    // private getPageInfo(): void {
    //     this.groupPage.total = this.tableDataList.length;
    //     this.tableData = getCurrentPageData(this.tableDataList, this.groupPage.currentPage, this.groupPage.pageSize);
    // }

    // 分页查询证券池
    private poolCurrentChange() {
        this.queryStockPoolList(this.currentData);
    }

    // 分页查询证券
    private async detailCurrentChange() {
        if (this.currentData.stGroupNodeType == 'FUND') {
            await this.getChildNode(this.currentData);
            this.queryFundStock(this.fundChildIds);
        } else {
            this.queryStockList(this.currentData);
        }
        // this.queryStockList(this.currentData);
    }

    // 查询证券池
    private queryStockPoolList(node: any) {
        this.tableLoading = true;
        let sourceTypeList = [];
        if (this.selectSourceType) {
            sourceTypeList = [this.selectSourceType];
        } else {
            if (node.stGrName == '本地') {
                sourceTypeList = ['1'];
            } else {
                // sourceTypeList = ['9'];
                sourceTypeList = ['2', '3', '4', '5', '6', '7', '8', '9'];
            }
        }

        let data = {
            keyword: this.inputValueRight,
            paging: {
                currentPage: this.groupPage.currentPage,
                pageSize: this.groupPage.pageSize,
            },
            sort: this.sortParam1,
            sourceTypeList: sourceTypeList,
        };
        this.$axios
            .post('/stockPool/stGroup/bySourceType', data)
            .then((res: any) => {
                this.tableData = res.list;
                this.groupPage.total = res.total;
                this.tableLoading = false;
            })
            .catch(() => {
                this.tableLoading = false;
            });
    }

    // 查询证券池下的证券
    private queryStockList(node: any) {
        this.tableLoading = true;
        let data = {
            keyword: this.inputDetailValueRight,
            paging: {
                currentPage: this.detailPage.currentPage,
                pageSize: this.detailPage.pageSize,
            },
            sort: this.sortParam2,
            stGrCode: node.stGrCode,
            stockPoolType: node.stockPoolType,
        };

        // if (node.stGroupNodeType == 'POOL' && node.stGrCode !== '-1' && node.stockCount > 0) {
        // if (node.stGrCode !== '-1' && node.stockCount > 0) {
        this.$axios
            .post('/stockPool/stock/queryStock/list', data)
            .then((res: any) => {
                this.tableData = res.list;
                this.detailPage.total = res.total;
                this.tableLoading = false;
            })
            .catch(() => {
                this.tableLoading = false;
            });
        // } else {
        //     this.tableData = [];
        //     this.detailPage.total = 0;
        // }
    }

    // 查询产品下的证券
    private queryFundStock(ids: any) {
        this.tableLoading = true;
        this.$axios
            .post('/stockPool/stock/queryStock/listByStGrCodeArr/v1', {
                paging: {
                    currentPage: this.detailPage.currentPage,
                    pageSize: this.detailPage.pageSize,
                },
                keyword: this.inputDetailValueRight,
                sort: this.sortParam2,
                stGrCodeList: ids,
            })
            .then((res: any) => {
                this.tableData = res.list;
                this.detailPage.total = res.total;
                this.tableLoading = false;
            })
            .catch(() => {
                this.tableLoading = false;
            });
    }

    // 根据父节点获取子节点
    async getChildNode(nodeObj: any) {
        let param: any = {
            fundCode: nodeObj.fundCode,
            stGrCode: '',
        };
        this.fundChildIds = [];
        await this.$axios
            .post('/stockPool/stGroup/node', param)
            .then((res: any) => {
                res.forEach(ele => {
                    if (ele.stGrCode !== '-1') {
                        this.fundChildIds.push(ele.stGrCode);
                    }
                });
            })
            .catch(() => {});
    }

    // 节点点击
    private async clickNode(data: any, node: any) {
        this.tableDataNum++;
        this.sortParam1 = '';
        this.sortParam2 = '';
        this.currentData = data;
        this.cutInfo = data.stGrName;
        if (this.cutInfo === '本地' || this.cutInfo === '外部') {
            this.queryStockPoolList(data);
        } else {
            if (data.stGroupNodeType == 'FUND') {
                await this.getChildNode(data);
                this.queryFundStock(this.fundChildIds);
            } else {
                this.queryStockList(data);
            }
        }
    }

    // 证券池查询
    private handleSearchPool(): void {
        this.groupPage.currentPage = 1;
        this.queryStockPoolList(this.currentData);
    }

    private handlePoolTableSort(column) {
        let sortType = column.order == 'ascending' ? 'ASC' : column.order == 'descending' ? 'DESC' : '';
        if (sortType) {
            this.sortParam1 = this.sortParamObj1[column.prop] + ' ' + sortType;
        } else {
            this.sortParam1 = '';
        }
        this.groupPage.currentPage = 1;
        this.queryStockPoolList(this.currentData);
    }

    private async handleStockTableSort(column) {
        let sortType = column.order == 'ascending' ? 'ASC' : column.order == 'descending' ? 'DESC' : '';
        if (sortType) {
            this.sortParam2 = this.sortParamObj2[column.prop] + ' ' + sortType;
        } else {
            this.sortParam2 = '';
        }
        this.detailPage.currentPage = 1;
        console.log(this.currentData, 'this.currentData');

        if (this.currentData.stGroupNodeType == 'FUND') {
            await this.getChildNode(this.currentData);
            this.queryFundStock(this.fundChildIds);
        } else {
            this.queryStockList(this.currentData);
        }
        // this.queryStockList(this.currentData);
    }

    // private clickNode(data: any): void {
    //     this.currentData = data;
    //     this.cutInfo = data.label;
    //     if (this.cutInfo === '本地' || this.cutInfo === '外部') {
    //         this.getGroupInfo();
    //         this.tableDataNum++;
    //     } else {
    //         this.tableDataNum++;
    //         // 这里判断是不是 外部 并且 tradeType为 5（维度类别为证券池的父节点）
    //         if (data.id.indexOf(this.PRE_FALSE) != -1) {
    //             // 过滤出其子树下面的全部id
    //             let data2 = this.filterIds(data.children);
    //             this.getDetailInfo2(data2);
    //         } else {
    //             this.getDetailInfo(data.id);
    //         }
    //     }
    // }

    // 递归子树的id
    // private filterIds(data = [], result = []) {
    //     for (let item of data) {
    //         result.push(item.id);
    //         if (item.children && item.children.length) {
    //             this.filterIds(item.children, result);
    //         }
    //     }
    //     return result;
    // }

    // 获取证券池数据
    // private getGroupInfo(): void {
    //     if (this.cutInfo === '本地') {
    //         this.tableDataList = this.localList;
    //     } else {
    //         this.tableDataList = this.outsideList;
    //     }
    //     this.selectGroup();
    // }

    // 获取证券池明细数据
    // private getDetailInfo(id: string): void {
    //     this.$axios.get('/stockPool/stock/queryStock/list/' + this.currentData.id).then((res: any) => {
    //         this.tableDataList = res;
    //         this.selectDetail();
    //     });
    // }

    // private getDetailInfo2(ids): void {
    //     this.$axios.post('/stockPool/stock/queryStock/listByStGrCodeArr', ids).then((res: any) => {
    //         this.tableDataList = res;
    //         this.selectDetail();
    //     });
    // }

    // 证券池查询
    // private selectGroup(): void {
    //     this.tableDataSearched = this.handleFilter(this.tableDataList, this.inputValueRight, 'stGrCode', 'stGrName');

    //     this.tableDataSearched = this.tableDataSearched.filter(item => {
    //         return (item.sourceType == this.selectSourceType || this.selectSourceType == '') && !(item.operatorName == this.FALSE_DATA);
    //     });
    //     this.groupPage.currentPage = 1;
    //     this.groupPageChange();
    // }

    // 证券池|| 明细筛选数据
    // private handleFilter(dataSource: any, param: any, code: string, name: string): any {
    //     if (!param || !dataSource) {
    //         return dataSource;
    //     } else {
    //         return dataSource.filter(
    //             (item: any) =>
    //                 (item[name] || '').toUpperCase().includes(param.toUpperCase()) || (item[code] || '').toUpperCase().includes(param.toUpperCase())
    //         );
    //     }
    // }

    // 证券池新增
    private addGroup(): void {
        this.groupData = JSON.parse(JSON.stringify(this.groupDataBackup));
        this.groupDialog = this.groupDialog.getAddDialog('新增证券池');
    }

    // 确认添加证券池
    private groupDialogConfirm(): void {
        if (!this.groupData.stGrName) {
            this.yh_message_error('证券池名称不能为空!');
            return;
        }
        if (this.groupDialog.action === 1) {
            this.$axios.post('/stockPool/stGroup/insert', this.groupData).then(res => {
                this.yh_message_success('新增成功');
                // this.getStockInfo();
                this.queryStockPoolList(this.currentData);
                this.groupDialogClosed();
            });
        } else {
            this.$axios.put('/stockPool/stGroup/update', this.groupData).then(res => {
                this.yh_message_success('编辑成功');
                // this.getStockInfo();
                this.queryStockPoolList(this.currentData);

                this.groupDialogClosed();
            });
        }
    }

    private groupDialogClosed(): void {
        this.groupDialog.visible = false;
    }

    // 证券池导出
    private downLoadGroupFile(): void {
        let type = this.cutInfo == '本地' ? '1' : '2';
        let data = this.hasSelectedData;
        if (this.hasSelectedData.length < 1 || !this.hasSelectedData) {
            // this.yh_message_warn('请选择导出的证券池');
            // return;
            data = XEUtils.map(this.tableDataList, item => item.stGrCode);
        }

        downLoadFile({
            url: '/stockPool/export/stock/pool/' + type,
            method: 'post',
            data: data,
        });
    }

    // 证券池删除
    private deleteGroup(): void {
        if (this.hasSelectedData.length < 1) {
            this.yh_message_warn('未选择删除项');
        } else {
            this.delPendingData = this.hasSelectedData;
            this.deleteDialog = this.deleteDialog.getDeleteDialog('确定删除证券池？');
        }
    }

    private deleteDialogClosed(): void {
        this.deleteDialog.visible = false;
    }

    // 确认删除
    private deleteDialogConfirm(): void {
        if (this.cutInfo === '本地' || this.cutInfo === '外部') {
            this.$axios({
                url: '/stockPool/stGroup/delete',
                method: 'DELETE',
                data: this.delPendingData,
            }).then(res => {
                this.yh_message_success('删除成功');
                // this.getStockInfo();
                this.queryStockPoolList(this.currentData);
                this.deleteDialogClosed();
            });
        } else {
            this.$axios({
                url: '/stockPool/stGroup/stock/delete/' + this.currentData.stGrCode,
                method: 'DELETE',
                data: this.delPendingData,
            }).then(res => {
                this.yh_message_success('删除成功');
                // this.getDetailInfo(this.currentData.id);
                this.queryStockList(this.currentData);
                this.deleteDialogClosed();
            });
        }
        this.hasSelectedData = [];
    }

    // 左侧搜索
    private submitInput(): void {}

    // 勾选
    private handleSelectionChange(data: any[]): void {
        this.hasSelectedData = XEUtils.map(data, item => item.stGrCode);
    }

    private handleSelectionDetailChange(data: any[]): void {
        this.hasSelectedData = XEUtils.map(data, item => item.stockCode);
    }

    // 表格编辑证券池
    private editGroupRow(row): void {
        this.groupDialog = this.groupDialog.getUpdateDialog('编辑证券池');
        this.groupData = JSON.parse(JSON.stringify(row));
    }

    // 表格删除证券池
    private deleteGroupRow(row: any): void {
        // this.delPendingData = [row.id];
        this.delPendingData = [row.stGrCode];
        this.deleteDialog = this.deleteDialog.getDeleteDialog('确定删除证券池？');
    }

    // 明细查询
    private async handleSearchDetail() {
        this.detailPage.currentPage = 1;
        if (this.currentData.stGroupNodeType == 'FUND') {
            await this.getChildNode(this.currentData);
            this.queryFundStock(this.fundChildIds);
        } else {
            this.queryStockList(this.currentData);
        }
        // this.queryStockList(this.currentData);
    }

    // 明细查询
    // private selectDetail(): void {
    //     this.tableDataSearched = this.handleFilter(this.tableDataList, this.inputDetailValueRight, 'stockCode', 'stockNameSt');
    //     this.detailPage.currentPage = 1;
    //     this.detailPageChange();
    // }

    // 编辑
    private editDetail(): void {
        this.editDetailDialog = this.editDetailDialog.getAddDialog('');
        this.rightTranData = this.tableData;
        // const filterCodes = XEUtils.map(this.rightTranData, item => item.stockCode);
        // this.$axios
        //     .post('/stockPool/stock/queryStock/stocklist', {
        //         filterCodes: filterCodes,
        //         keyName: '',
        //         paging: {
        //             currentPage: 1,
        //             pageSize: 50,
        //         },
        //     })
        //     .then((res: any) => {
        //         this.leftTranData = res.list;
        //     });
    }

    // 明细编辑确认
    private editDetailDialogConfirm(): void {
        let needData = [];
        const rightData = (this.$refs.tranTable as any).getRightAllData();
        rightData.map((item: any) => {
            needData.push(item.stockCode);
        });
        this.$axios.post('/stockPool/stGroup/insert/stock/' + this.currentData.stGrCode, needData).then((res: any) => {
            this.yh_message_success('编辑成功');
            // this.getDetailInfo(this.currentData.id);
            this.queryStockList(this.currentData);
            this.editDetailDialogClosed();
        });
    }

    // 关闭编辑弹窗
    private editDetailDialogClosed(): void {
        this.editDetailDialog.visible = false;
    }

    //  导出明细
    private downLoadDetailFile(): void {
        console.log(this.currentData, 'nodeee');

        let data = this.hasSelectedData;
        if (this.hasSelectedData.length < 1 || !this.hasSelectedData) {
            // this.yh_message_warn('请选择导出的证券池明细');
            // return;
            data = XEUtils.map(this.tableDataList, item => item.stockCode);
        }
        let params = {
            isGrCode: '',
            fundCode: '',
            dimlayerCode: '',
            rowSelection: data,
            stGroupNodeType: this.currentData.stGroupNodeType,
        };
        let type = this.currentData.stGroupNodeType;
        if (type == 'POOL') {
            params.isGrCode = this.currentData.stGrCode;
        } else if (type == 'FUND' || type == 'NO_FUND') {
            params.fundCode = this.currentData.fundCode;
        } else if (type == 'DIMENSION_LAYER') {
            params.fundCode = this.currentData.fundCode;
            params.dimlayerCode = this.currentData.dimensionLayerCode ?? '';
        }
        downLoadFile({
            url: '/stockPool/export/stock',
            method: 'post',
            data: params,
        });
    }

    // 删除明细
    private deleteDetail(): void {
        if (this.hasSelectedData.length < 1) {
            this.yh_message_warn('未选择删除项!');
        } else {
            this.delPendingData = this.hasSelectedData;
            this.deleteDialog = this.deleteDialog.getDeleteDialog('确认删除证券池内证券？');
        }
    }

    private nodeArr: any[] = [];

    // 递归数组转成树，父节点是属性hsParentId值为-1的
    tranListToTreeData(list, pid = -1) {
        // 先找到所有的根节点
        let tranList = list.filter(it => it.hsParentId == pid);
        tranList.forEach(item => {
            // 传入id  list进行递归 在筛选出 他的父级 是一个数组
            item.children = this.tranListToTreeData(list, item.id);
        });
        this.nodeArr = this.nodeArr.concat(tranList);
        return tranList;
    }

    toTreeData(list) {
        // 缩小需要处理数据范围， listTemp 会影响 list 的数值
        let listTemp = list.filter(i => i.tradeType == '5' && i.hsParentId == '-1');
        // 产品信息排序
        for (let i of this.fundCodeArr) {
            // 找到fundCode这个的能对应证券池的数据
            let temp = listTemp.filter(item => item.fundCode == i);
            temp.forEach(item => {
                item.hsParentId = this.PRE_FALSE + i;
            });
            let fundCodeName = this.fundCodeTradeTypeArr.find(item => item.split('_')[0] == i);
            fundCodeName = fundCodeName.split('_')[1];
            // 全公司
            let label = i == '-1' ? fundCodeName : i + '-' + fundCodeName;
            // 父节点
            list.push({
                label: label,
                id: this.PRE_FALSE + i,
                dtCtDate: 20220916,
                dtCtTime: 40420,
                dtCtUser: 'SYSDBO',
                hsParentId: -1,
                operatorName: this.FALSE_DATA,
                sourceType: '2',
                stGrCode: this.PRE_FALSE + i,
                tradeType: '5',
            });
        }
        // 数据移动到最后
        let listTemp2 = listTemp.filter(i => !this.fundCodeArr.includes(i.fundCode));
        if (listTemp2 && listTemp2.length) {
            console.info('维度类别为证券池的数据有的fundCode不在产品信息，故进来这步，打印这句话');
            listTemp2.forEach(item => {
                // 改变它的父节点
                item.hsParentId = '$/' + item.hsParentId;
            });
        }
        let tranList = this.tranListToTreeData(list);
        // 添加父节点在数据中不存在的节点
        if (list.length > this.nodeArr.length) {
            // 差集
            let tempArr = [...new Set(list)].filter(item => !new Set(this.nodeArr).has(item));
            tranList = tranList.concat(tempArr);
        } else {
            this.nodeArr = [];
        }
        return tranList;
    }

    // 获取下拉框数据
    private getDictionaryData(code: any): void {
        this.$axios.get('/dict/list/code/' + code).then((res: any) => {
            this.tradeTypeArr = res;
            this.tradeTypeArr.unshift({ dictCode: code, dictKey: '', dictKeyName: '全部' });
        });
    }

    // 需求针对证券池类别做特殊处理
    queryFundCodeTradeType5() {
        this.$axios.get('/stockPool/queryFundCodeTradeType5').then((res: any) => {
            if (res) {
                res.unshift('-1_全公司');
                this.fundCodeArr = res.map(i => i.split('_')[0]);
                this.fundCodeArr = [...new Set(this.fundCodeArr)];
                this.fundCodeTradeTypeArr = res;
            }
        });
    }
}
</script>
<style lang="scss" scoped>
.pool-list {
    position: relative;
    height: 100%;
    .selectStyle {
        width: 160px;
        margin-right: 10px;
    }
    .dict-r-slot {
        margin-left: 10px;
    }
}
/deep/ .el-dialog .el-dialog__body {
    max-height: 100vh;
}

/deep/ .editDialog .el-dialog {
    margin-top: 10vh !important;
    .el-dialog__body {
        padding: 10px;
        max-height: 90vh;
    }
}
/deep/ .el-table--border th:first-child .cell {
    padding-left: 6px;
}
.is-leaf.el-tree-node_expand-icon {
    display: none；;
}
</style>
